package com.gxa.admin.service.impl;

import com.gxa.admin.config.JwtTokenUtils;
import com.gxa.admin.pojo.Emp;
import com.gxa.admin.pojo.JwtEmp;
import com.gxa.admin.pojo.dto.EmpLoginDto;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.security.authentication.BadCredentialsException;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.stereotype.Service;

import java.util.List;
import java.util.stream.Collectors;

/**
 * @author IKE <hp1041735092@outlook.jp>
 * @date 21/3/2024
 */
@Service
@Slf4j
@RequiredArgsConstructor(onConstructor = @__(@Autowired))
public class AuthEmpService {
    private final EmpService empService;
    private final StringRedisTemplate stringRedisTemplate;
    /**
     * 验证用户信息,通过后生成token
     */
    public String createToken(EmpLoginDto empLoginDto) {
        Emp emp = empService.find(empLoginDto.getEmpAccount());

        log.info(emp.toString());
        boolean flag =empService.check(empLoginDto.getEmployeePwd(),emp.getEmployeePwd()); //验证成功flag=true
        if (!flag){
            throw new BadCredentialsException("用户名或密码有误~~~");
        }
        JwtEmp jwtEmp = new JwtEmp(emp);
        if (!jwtEmp.isEnabled()){
            throw new BadCredentialsException("用户被禁止登录~~~");
        }
        List<String> authorities = jwtEmp.getAuthorities()
                .stream()
                .map(GrantedAuthority::getAuthority)
                .collect(Collectors.toList());

        //签发jwt token,包含用户基础信息和权限信息
        String token = JwtTokenUtils.createToken(
                emp.getEmployeeName(),
                emp.getEmployeeId().toString(),
                authorities,
                true);

        //使用redis保存token,调用登出接口的时候,在redis里使token过期
        stringRedisTemplate.opsForValue().set(emp.getEmployeeId().toString(),token);

        return token;
    }

}
